<?php

/*
 * Edit by shengxin
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */
namespace api\mall\controller;

use api\mall\model\UserMoveModel;
use api\mall\model\AddressModel;
use app\user\model\UserModel;
use api\mall\model\UserAuditModel;
use api\user\model\UserScoreLogModel;
use think\facade\Db;

use cmf\controller\RestBaseController;

use api\portal\service\UserInfoService;
use app\portal\model\UserRealNameInfoModel;
use app\portal\model\UserBehaviorModel;

/**
 * @OA\Tag(
 *     name="mall-user",
 *     description="客户端用户管理"
 * )
 */
class UserController extends RestBaseController{
    
    protected function initialize() {
        parent::initialize();
        if(empty($this->user)){
            $this->error('login');
        }
        online_record($this->userId);
    }

    /**
     * token登录
     * @OA\Get(
     *     tags={"mall-user"},
     *     path="/mall/user/tokenLogin",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function tokenLogin() {
        $userModel = new UserModel();
        $user = $userModel->where('id', $this->getUserId())->find();
        if (empty($user)) {
            $this->error('用户不存在');
        }

        $userInfoService = new UserInfoService();
        $userInfoService->updateUserLoginLog($user);
        $userInfoService->updateUserFriendNum($user['id']);
        
        $user['avatar'] = cmf_get_image_url($user['avatar']);

        $user['needSetPassword'] = false;
        $user['needSetAvatar'] = false;
        $user['needSetRealName'] = false;
        if (empty($user['user_pass']) || strlen($user['user_pass']) <= 0) {
            $user['needSetPassword'] = true;
        }
        if ($user['sex'] < 0) {
            $user['needSetAvatar'] = true;
        }
        $userRealNameInfoModel = new UserRealNameInfoModel();
        if (empty($userRealNameInfoModel->where('user_id', $user['id'])->find())) {
            $user['needSetRealName'] = true;
        }
        
        unset($user['user_pass']);

        $api = new \Tencent\TLSSigAPIv2(1600020287, '72bdae2f2efe09bdc5404710fdbe814d23a211dc775af6cbfafa2466f460a9d4');
        $sig = $api->genUserSig($user['id']);
        $user['im_sign'] = $sig;

        $user['pay_pass'] = (empty($user['pay_pass']) || strlen($user['pay_pass']) <= 0)?1:0;
        
        $this->success('ok', $user);
    }

    /**
     * 登出
     * @OA\Get(
     *     tags={"mall-user"},
     *     path="/mall/user/logout",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function logout() {
        Db::name('user_token')->where([
            'token'       => $this->token,
            'user_id'     => $this->userId,
            'device_type' => $this->deviceType
        ])->update(['token' => '']);

        $this->success("退出成功!");
    }
    
    /**
     * 首次登录设置密码
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/firstSetPassword",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="user_pass", type="string", example=""),
     *             @OA\Property(property="user_pass_repeat", type="string", example="")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function firstSetPassword()
    {
        $data = $this->request->post();
        do {
            if (empty($data['user_pass'])) {
                $result = '密码不能为空';
                break;
            }
            if (empty($data['user_pass_repeat'])) {
                $result = '重复密码不能为空';
                break;
            }
            if ($data['user_pass'] != $data['user_pass_repeat']) {
                $result = '密码不一致，请重新输入！';
                break;
            }

            $userInfoService = new UserInfoService();
            if (false == $userInfoService->passwordValidate($data['user_pass'])) {
                $result = '密码格式错误，密码格式为8-16位，并且由大小写字母、数字、英文特殊符号两种以上组合';
                break;
            }

            $userModel = new UserModel();
            $user = $userModel->where('id', $this->userId)->find();
            if (empty($user)) {
                $result = '用户不存在';
                break;
            }
            if (strlen($user['user_pass']) > 0) {
                $result = '密码已经存在，不能重复设置';
                break;
            }

            $update = [];
            $update['user_pass'] = cmf_password($data['user_pass']);
            $userModel->where('id', $this->userId)->update($update);
            $this->success('ok');
        } while (false);
        $this->error($result);
    }

    /**
     * 获取默认头像和昵称
     * @OA\Get(
     *      tags={"mall-user"},
     *      path="/mall/user/defaultAvatarAndNick",
     *  @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function defaultAvatarAndNick()
    {
        $data = [];
        $mall = cmf_get_option('mall');
        $data['default_male_nick'] = (isset($mall['default_male_nick']) ? $mall['default_male_nick'] : '');
        $data['default_female_nick'] = (isset($mall['default_female_nick']) ? $mall['default_female_nick'] : '');
        $data['default_male_avatar'] = (isset($mall['default_male_avatar']) ? cmf_get_image_url($mall['default_male_avatar']) : '');
        $data['default_female_avatar'] = (isset($mall['default_female_avatar']) ? cmf_get_image_url($mall['default_female_avatar']) : '');
        $this->success('ok', $data);
    }

    /**
     * 首次登录设置性别和昵称
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/firstSetSexAndNick",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="sex", type="integer", example=""),
     *             @OA\Property(property="user_nickname", type="string", example="")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function firstSetSexAndNick()
    {
        $data = $this->request->post();
        do {
            if (!isset($data['sex']) || empty($data['sex']) || ($data['sex'] != 1 && $data['sex'] != 2)) {
                $result = '性别无效';
                break;
            }
            if (!isset($data['user_nickname']) || empty($data['user_nickname'])) {
                $result = '用户名不能为空';
                break;
            }

            $userModel = new UserModel();
            $user = $userModel->where('id', $this->userId)->find();
            if (empty($user)) {
                $result = '用户不存在';
                break;
            }
            // 昵称重复判断
            if ($userModel->where('user_nickname', $data['user_nickname'])->find()) {
                $result = '昵称已经存在';
                break;
            }
            // if ($user['sex'] > 0) {
            //     $result = '性别已经存在，不能重复设置';
            //     break;
            // }

            // $userAuditModel = new UserAuditModel();
            // $auditCount = $userAuditModel->where('user_id', $this->userId)->where('audit_status', 0)->whereNotNull('audit_nickname')->count();
            // if (0 < $auditCount) {
            //     $result = '请等待之前昵称审核完成再做修改'.$this->userId;
            //     break;
            // }

            // if (!empty($data['user_nickname'])) {
            //     $dataIns = [];
            //     $dataIns['user_id']= $this->userId;
            //     $dataIns['create_time'] = time();
            //     $dataIns['audit_nickname'] = $data['user_nickname'];
            //     $dataIns['before_avatar'] = $user['avatar'];
            //     $dataIns['before_nickname'] = $user['user_nickname'];
            //     $userAuditModel->insert($dataIns);
            // }

            $update = [];
            $update['sex'] = $data['sex'];
            $update['user_nickname'] = $data['user_nickname'];
            $mall = cmf_get_option('mall');
            $update['avatar'] = $data['sex'] == 1 ? 
                (isset($mall['default_male_avatar']) ? $mall['default_male_avatar'] : '') : 
                (isset($mall['default_female_avatar']) ? $mall['default_female_avatar'] : '');
            $userModel->where('id', $this->userId)->update($update);
            
            $update['avatar'] = cmf_get_image_url($update['avatar']);
            $this->success('ok', $update);
        } while (false);
        $this->error($result);
    }

    // /**
    //  * 更换手机号码
    //  * @OA\Post(
    //  *     tags={"mall-user"},
    //  *     path="/mall/user/changeMobile",
    //  *     @OA\RequestBody(
    //  *         @OA\JsonContent(
    //  *             type="object",
    //  *             @OA\Property(property="mobile", type="string", example="18845456666"),
    //  *             @OA\Property(property="code", type="integer", example=4444)
    //  *         )
    //  *     ),
    //  *     @OA\Response(response=200, ref="#/components/responses/200")
    //  * )
    //  */
    // public function changeMobile()
    // {
    //     $data = $this->request->post();
    //     do {
    //         if (empty($data['mobile']) || !cmf_check_mobile($data['mobile'])) {
    //             $result = '请输入正确的手机号码';
    //             break;
    //         }
    //         if (empty($data['code'])) {
    //             $result = '验证码不能为空';
    //             break;
    //         }
            
    //         $userModel = new UserModel();
    //         $user = $userModel->where('mobile', $data['mobile'])->find();
    //         if (！empty($user)) {
    //             $result = '该手机号已经与其它账号绑定！';
    //             break;
    //         }

    //         $result = cmf_check_verification_code($data['mobile'], $data['code'], true);
    //         if ($result !== true) {
    //             break;
    //         }

    //         //清理验证码
    //         if ($data['code'] != "4444") {
    //             cmf_clear_verification_code($data['mobile']);
    //         }

    //         $update = [];
    //         $update['mobile'] = $data['mobile'];
    //         $userModel->where('id', $this->userId)->update($update);

    //         Db::name('user_token')->where([
    //             'token'       => $this->token,
    //             'user_id'     => $this->userId,
    //             'device_type' => $this->deviceType
    //         ])->update(['token' => '']);

    //         $this->success('ok');
    //     } while (false);
    //     $this->error($result);
    // }
    
    /**
     * 移动
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/move",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="x", type="integer", example=""),
     *             @OA\Property(property="y", type="integer", example=""),
     *             @OA\Property(property="z", type="integer", example=""),
     *             @OA\Property(property="o", type="integer", example="")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function move(){
        $now = time();
        $user = $this->user;
        $data = $this->request->post(); 
//        $result  = $this->validate(
//            $position,
//            [
//                'x' => 'require|integer',
//                'y' => 'require|integer',
//                'y' => 'require|integer'
//            ],
//            [
//                'x.require' => '坐标x！',
//                'x.integer'     => '',
//                
//                'y.require' => '坐标y！',
//                'y.integer'     => '',
//              
//                'z.require' => '坐标z！',
//                'z.integer'     => '',
//              
//                'o.require' => '坐标o！',
//                'o.integer'     => ''
//            ]
//        );

//        if (true !== $result) {
//            // 验证失败 输出错误信息
//            $this->error($result);
//        }
        
        $position = [
            'x'=>empty($data['x'])?0:$data['x'],
            'y'=>empty($data['y'])?0:$data['y'],
            'z'=>empty($data['z'])?0:$data['z'],
            'o'=>empty($data['o'])?0:$data['o']
        ];
        $position['uid'] = $user->id;       
        $position['update_time'] = $now;
        $save = array_merge($position,['user_nickname'=>$user->user_nickname,'avatar' => $user->avatar]);
        $model = new UserMoveModel();
        $model->duplicate($position)->save($save);
        //我敢认定同时在线的人不会太多
        //所以这里就这么干
        $list = $model->field('uid,x,y,z,o,user_nickname,avatar')->where('update_time','>',$now-100)->limit(30)->select();
        $uids = [];
        foreach ($list as &$v){
            $uids[] = $v['uid'];
            $v['medal'] = 0;
            $v['avatar'] = cmf_get_image_url($v['avatar']);
        }
        $medalModel = new \api\mall\model\MedalUserModel();
        $medals = $medalModel->whereIn('user_id',$uids)->where('status_i',1)->select();
        foreach ($medals as $mu){
            $uid = $mu['user_id'];
            foreach ($list as &$u){
                if($u['uid']==$uid){
                    $u['medal'] = $mu['medal_id'];
                    break;
                }
            }
        }
        // $test = $list[0];
        // $testList = [];
        // for ($i = 0; $i < 30; $i++) {
        //     array_push($testList, $test);
        // }
        $this->success('ok', $list);
    }
    
    /**
     * 编辑用户信息
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/editUser",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="user_nickname", type="string", example=""),
     *             @OA\Property(property="user_pass", type="string", example=""),
     *             @OA\Property(property="mobile", type="string", example="18845456666"),
     *             @OA\Property(property="code", type="integer", example=4444),
     *             @OA\Property(property="avatar", type="string", example="avatar/20240121/9f5c25934a32da9010b6dcddd4c4144c.jpg")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function editUser(){
        $data = $this->request->post();
        $result  = $this->validate(
            $data,
            [
                'user_nickname' => 'string|length:2,20',   
                'user_pass' => 'string|length:8,20',   
                'mobile' => 'mobile',
                'code'=>'length:6',
                'avatar' => 'string|length:51,100'
            ],
            [
                'mobile.mobile' => '手机号码不正确！',
                'user_nickname.length' => '名称超过最大长度！！',
                'avatar.length' => '头像长度不合法 例 avatar/20240121/9f5c25934a32da9010b6dcddd4c4144c.jpg'
            ]
        );

        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        
        $update = [];
        if (isset($data['user_pass'])){
            $update['user_pass'] = cmf_password($data['user_pass']);
        }
        if (isset($data['user_nickname'])){
            $update['user_nickname'] = $data['user_nickname'];
        }
        if (isset($data['mobile'])){
            $userModelFind = new UserModel();
            $userFind = $userModelFind->where('mobile', $data['mobile'])->find();
            if (!empty($userFind)) {
                $this->error('该手机号已经与其它账号绑定！');
            }
            if(empty($data['code'])){
                $this->error('验证码不能为空');
            }
            $result = cmf_check_verification_code($data['mobile'], $data['code'], true);
            if($result!==true){
                if (strpos($result, '过期') !== false) {
                    $result = "验证码已过期，请重新获取";
                }
                if (strpos($result, '验证码不正确') !== false) {
                    $result = "验证码不匹配，请重新输入";
                }
                $this->error($result);
            }
            //清理验证码
            if ($data['code'] != "4444") {
                cmf_clear_verification_code($data['mobile']);
            }
            $update['mobile'] = $data['mobile'];    
            $update['user_login'] = $data['mobile'];    
        }
        if (isset($data['avatar'])){
            $update['avatar'] = $data['avatar'];
        }

        if(empty($update)){
            $this->success('干啥呢');
        }

        // $userAuditModel = new UserAuditModel();
        // if (!empty($data['user_nickname'])) {
        //     $auditCount = $userAuditModel->where('user_id', $this->userId)->where('audit_status', 0)->whereNotNull('audit_nickname')->count();
        //     if (0 < $auditCount) {
        //         $this->error('请等待之前昵称审核完成再做修改');
        //     }
        // }
        // if (!empty($data['avatar'])) {
        //     $auditCount = $userAuditModel->where('user_id', $this->userId)->where('audit_status', 0)->whereNotNull('audit_avatar')->count();
        //     if (0 < $auditCount) {
        //         $this->error('请等待之前头像审核完成再做修改');
        //     }
        // }
        // if (!empty($data['user_nickname']) || !empty($data['avatar'])) {
        //     $dataIns = [];
        //     $dataIns['user_id']= $this->userId;
        //     $dataIns['create_time'] = time();
        //     $dataIns['audit_nickname'] = !empty($data['user_nickname']) ? $data['user_nickname'] : '';
        //     $dataIns['audit_avatar'] = !empty($data['avatar']) ? $data['avatar'] : '';
        //     $dataIns['before_avatar'] = $this->user->avatar;
        //     $dataIns['before_nickname'] = $this->user->user_nickname;
        //     $userAuditModel->insert($dataIns);
        // }

        $umodel = new UserModel();
        $umodel->where('id',$this->userId)->update($update);
        //移动表里有昵称副本,删除
        $model = new UserMoveModel();
        $model->where('uid',$this->userId)->delete();
        $this->success('ok');
    }
    
    /**
     * 获取最近一条审核记录 用来在编辑头像和昵称时显示是否已经在审核
     * @OA\Get(
     *     tags={"mall-user"},
     *     path="/mall/user/latestAudit",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function latestAudit() {
        $userAuditModel = new UserAuditModel();
        $auditData = $userAuditModel->where('user_id', $this->userId)->where('audit_status', 0)->order('create_time desc')->select();
        $this->success('ok',$auditData);
    }

    /**
     * 获取地址
     * @OA\Get(
     *     tags={"mall-user"},
     *     path="/mall/user/address",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function address(){
        $addressModel = new AddressModel();
        $address = $addressModel->where('uid',$this->userId)->order('is_default','desc')->order('id','desc')->select();
        $this->success('ok',$address);
    }

    /**
     * 编辑用户信息
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/deleteAddress",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="id", type="integer", example=""),
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function deleteAddress(){
        $data = $this->request->post();
        $result  = $this->validate(
            $data,
            [
                'id' => 'require|integer',
            ],
            [
                'id.require' => '地址id必填！',
                'id.integer'     => '地址id不合法！',
            ]
        );
        
        if (true !== $result) {
            $this->error($result);
        }
        // 判断地址是否存在
        if (!AddressModel::where('uid',$this->userId)->where('id',$data['id'])->find()) {
            $this->error('地址不存在');
        }
        
        $addrModel = new AddressModel();
        $addrModel->where('uid',$this->userId)->where('id',$data['id'])->delete();
        $this->success('ok');
    }
    
    /**
     * 编辑用户信息
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/editAddress",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="province", type="string", example=""),
     *             @OA\Property(property="city", type="string", example=""),
     *             @OA\Property(property="district", type="string", example=""),
     *             @OA\Property(property="real_name", type="string", example=""),
     *             @OA\Property(property="phone_number", type="string", example=""),
     *             @OA\Property(property="detail", type="string", example=""),
     *             @OA\Property(property="is_default", type="integer", example=""),
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function editAddress(){
        $data = $this->request->post();
        
        $result  = $this->validate(
            $data,
            [
                'province' => 'require|max:20',
                'city' => 'require|max:20',
                'district' => 'require|max:20',
                'street' => 'require|max:20',
                'real_name' => 'require|max:20',
                'phone_number' => 'require|mobile',
                'detail' => 'require|max:120',                
                'is_default' => 'integer',

            ],
            [
                'province.require' => '省份必填！',
                'province.max'     => '省份名称超过最大长度！！',
                
                'city.require' => '所在市必填！',
                'city.max'     => '所在市名称超过最大长度！！',
                
                'district.require' => '区必填！',
                'district.max'     => '区名称超过最大长度！！',
                
                'street.require' => '街道必填！',
                'street.max'     => '街道名称超过最大长度！！',
                
                'real_name.require' => '收货人姓名必填！',
                'real_name.max'     => '姓名超过最大长度！！',
                
                'detail.require' => '详细收货地址必填！',
                'detail.max'     => '收货地址超过最大长度！！',
                
                'phone_number.require' => '手机号必填！',
                'phone_number.mobile'     => '手机号码不正确！！',
            ]
        );

        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        $addrModel = new AddressModel();
        if($data['is_default']){
            $addrModel->where('uid',$this->userId)->update(['is_default'=>0]);
        }
        
        $data['uid']= $this->userId;
        $data['update_time'] = time();
        if(isset($data['id'])){
            $addrModel->where('uid',$this->userId)->where('id',$data['id'])->update($data);
        }else{
            $data['create_time'] = time();
            $addrModel->insert($data);
        }
        $this->success('ok',$data);
    }
    
    
    /**
     * 请求发送验证码
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/sendCode",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function sendCode()
    {
        $user = $this->user;
        do {
            $mobile = $user['mobile'];
            $code = cmf_get_verification_code($mobile);
            if (false == $code) {
                $result = '验证码获取频繁，请稍后再试';
                break;
            }

            $smsModel = new \plugins\tencentcloud_sms\TencentcloudSmsPlugin();
            $sendResult = $smsModel->sendMobileVerificationCode(['mobile' => $mobile, 'code' => $code]);
            if (false == $sendResult) {
                $result = '验证码发送失败，请稍后再试';
                break;
            }

            cmf_verification_code_log($mobile, $code, time()+5*60);
            $this->success('验证码发送成功');
        } while (false);
        $this->error($result);
    }
    
    /**
     * 重置支付密码,重置之前发送验证码
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/resetPayPass",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="pay_pass", type="string", example="新支付密码,888888"),
     *             @OA\Property(property="code", type="string", example="手机验证码,234432")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function resetPayPass() {
        $data = $this->request->post();
        $user = $this->user;
        $code = $data['code'];
        $result = cmf_check_verification_code($user['mobile'], $code, true);
        if ($result !== true) {
            if (strpos($result, '过期') !== false) {
                $result = "验证码已过期，请重新获取";
            }
            if (strpos($result, '验证码不正确') !== false) {
                $result = "验证码不匹配，请重新输入";
            }
            $this->error($result);
        }
        $passwd = $data['pay_pass'];
        if(empty($passwd)|| strlen($passwd)!=6){
            $this->error('密码长度必须为6位');
        }
        $encrypt = cmf_password($passwd);
        
        $model = new UserModel();
        $model->where('id',$this->userId)->update(['pay_pass'=>$encrypt]);
        $this->success('修改成功');
    }
    
    /**
     * 设置我已经购买的数字藏品的展位
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/set_booth_idx",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="item_id", type="string", example="我的数字藏品的物品ID:cf23232fa888"),
     *             @OA\Property(property="index", type="integer", example="展位索引: 3")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function set_booth_idx(){
        $id = $this->request->post('item_id');
        $idx = $this->request->post('index');
        $model = Db::name('digital_collect');
        $model->where('user_id',$this->userId)->where('booth_idx',$idx)->update(['booth_idx'=>0]);
        $model = Db::name('digital_collect');
        $model->where('user_id',$this->userId)->where('item_id',$id)->update(['booth_idx'=>$idx]);
        $this->success('设置成功');
    }
    
    /**
     * 轮训
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/polling",
     *     summary="客户端和服务器端的定时轮训.统计用户在线时长.增加用户是否拉黑状态",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="status", type="int", example="1:表示正常,0:表示后台运行")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function polling(){
        $result = [];
        $result['user_status'] = $this->user['user_status'];
        $result['chat_change_time'] = $this->user['chat_change_time'];
        $this->success('ok', $result);
    }
    
    
    
    /**
     * 获取钱包口令
     * @OA\Get(
     *     tags={"mall-user"},
     *     path="/mall/user/walletCode",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function walletCode() {
        $walletCodeQuery = Db::name('wallet_code');
        $currentTime = time();
        $maxCount = 5;
        $findWalletCode = $walletCodeQuery->where('id', $this->userId)->find();
        $result = false;
        if (empty($findWalletCode)) {
            $result = true;
        } else {
            $endTime = $findWalletCode['send_time'];
            $todayStartTime = strtotime(date('Y-m-d', $currentTime));
            if ($endTime < $todayStartTime) {
                $result = true;
            } else if ($findWalletCode['count'] < $maxCount) {
                $result = true;
            }
        }
    
        if ($result) {
            $userInfoService = new UserInfoService();
            $result = $userInfoService->generateActivationCode(10);

            $expireTime = $currentTime + 15 * 60;

            if ($findWalletCode) {
                $todayStartTime = strtotime(date("Y-m-d"));
                if ($findWalletCode['send_time'] <= $todayStartTime) {
                    $count = 1;
                } else {
                    $count = Db::raw('count+1');
                }
                Db::name('wallet_code')
                    ->where('id', $this->userId)
                    ->update([
                        'send_time'   => $currentTime,
                        'expire_time' => $expireTime,
                        'code'        => $result,
                        'count'       => $count
                    ]);
            } else {
                Db::name('wallet_code')
                    ->insert([
                        'id'     =>  $this->userId,
                        'send_time'   => $currentTime,
                        'code'        => $result,
                        'count'       => 1,
                        'expire_time' => $expireTime
                    ]);
            }
            $this->success('ok', $result);
        }
        else {
            $this->error('获取频繁，请稍后再试');
        }
    }


    /**
     * 用户财富详情 score可兑换 coin可消费 balance总额
     * @OA\Get(
     *     tags={"mall-user"},
     *     path="/mall/user/financeDetail",
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function financeDetail() {
        $userScoreLogModel = new UserScoreLogModel();
        $data = [];
        $data['score'] = $this->user['score'];
        $data['coin'] = $this->user['coin'];
        $data['balance'] = $this->user['balance'];        
        $data['score_detail_30'] = 
            $userScoreLogModel
            ->where('user_id', $this->userId)
            ->where('score', '<>', 0)
            ->where('create_time', '>', time() - 30 * 24 * 3600)
            ->order('id desc')
            ->select();
        $data['coin_detail_30'] = 
            $userScoreLogModel
            ->where('user_id', $this->userId)
            ->where('coin', '<>', 0)
            ->where('create_time', '>', time() - 30 * 24 * 3600)
            ->order('id desc')
            ->select();
        $data['balance_detail_30'] = 
            $userScoreLogModel
            ->where('user_id', $this->userId)
            ->where('balance', '<>', 0)
            ->where('create_time', '>', time() - 30 * 24 * 3600)
            ->order('id desc')
            ->select();
        $this->success('ok', $data);
    }
        
    /**
     * 用户行为统计
     * @OA\Post(
     *     tags={"mall-user"},
     *     path="/mall/user/behavior",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="behavior_type", type="integer", example="1浏览 2加入购物车 3生成订单 4支付订单 5完成交易")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function behavior()
    {
        do {
            $data = $this->request->post();
            if (empty($data['behavior_type'])) {
                $result = '行为类型不能为空';
                break;
            }
            $behaviorType = $data['behavior_type'];
            if (!in_array($behaviorType, [1, 2, 3, 4, 5])) {
                $result = '行为类型不正确';
                break;
            }
            $model = new UserBehaviorModel();
            if (!$model->where('user_id', $this->userId)->find()) {
                $model->insert(['user_id' => $this->userId, 'create_time' => time(), 'update_time' => time()]);
            }

            $update = [];
            switch ($behaviorType) {
                case 1:
                    $update['browse'] = 1;
                    break;
                case 2:
                    $update['add_cart'] = 1;
                    break;
                case 3:
                    $update['create_order'] = 1;
                    break;
                case 4:
                    $update['pay_order'] = 1;
                    break;
                case 5:
                    $update['complete_deal'] = 1;
                    break;
            }
            $update['update_time'] = time();
            $model->where('user_id', $this->userId)->update($update);
            $this->success('更新成功');
        } while (false);
        $this->error($result);
    }
    
    /**
     * 获取其他用户用户信息,少量字段
     * @OA\Get(
     *     tags={"mall-user"},
     *     path="/mall/user/getUserData",
     *     summary="获取其他用户用户信息",
     *     security={{ "Bearer":{} }},
     *      @OA\Parameter(
     *         name="id",
     *         @OA\Schema(
     *             type="int",
     *             format="id"
     *         ),
     *         in="query",
     *         description="用户ID",
     *         example="4",
     *         required=true,
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function getUserData(){
        $uid = $this->request->get('id/d');
        $userModel = new UserModel();
        $user = $userModel->field('user_nickname,id,avatar')->where('id', $uid)->find();
        if (empty($user)) {
            $this->error('用户不存在');
        }
        $user['avatar'] = cmf_get_image_url($user['avatar']);
//        $medal = new \api\mall\model\MedalUserModel();
//        $rs = $medal->alias('mu')->join('medal md','md.id=mu.medal_id')
//                ->field('medal_key,medal_name,medal_url,status_i,mu.id')->where('user_id',$uid)->order('mu.id asc')->select();
//        $medals = [
//            'num_0'=>0,
//            'num_1'=>0
//            ];
//        if($rs){
//            foreach ($rs as $md){
//                $md['']
//                $type = $md['medal_key'];
//                $medals['new_'.$type] = $md;
//                $medals['num_'.$type]++;
//                if($md['status_i']){
//                    $medals['wear'] = $md;
//                }
//            }
//        }
//  
//        $user['medals'] = $medals;
        $this->success('ok',$user);
    }
}
